<?php
namespace app\api\controller;

use app\common\controller\IndexBaseController;
use app\common\model\Member;
use app\web\model\LineMemberModel;
use app\web\model\OrderModel;
use think\Db;
/**
 * 支付接口
 */
class PaymentController extends IndexBaseController {
	
	protected function _initialize() {
			 parent::_initialize();
	}
	/**
	 * 判断订单是否已经支付过
	 */
	public function check_order(){
		$where['sn']=input('WIDout_trade_no');
		$where['status']=2;
		$paylog=db("mall_paylog")->where($where)->find();
		if($paylog){
			return $this->toJson(408, '请勿重复支付');
		}
	}
	

	/**
	 * 支付宝手机支付
	 * $params
	 */
	public function alipay($params = '') {
		$this->check_order();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipaySubmit");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		//合作身份者ID，签约账号，以2088开头由16位纯数字组成的字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		//收款支付宝账号，以2088开头由16位纯数字组成的字符串，一般情况下收款账号就是签约账号
		$alipay_config['seller_id'] = $payment_config['alipay_seller_id'];
		// MD5密钥，安全检验码，由数字和字母组成的32位字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['key'] = $payment_config['alipay_key'];
		// 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
		$alipay_config['notify_url'] = url("payment/alipay_notify", '', '', true);
		if($_POST['type']=="xs_order"){
			// 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
			$alipay_config['return_url'] = url("payment/alipay_return1", '', '', true);
		}else{
			$alipay_config['return_url'] = url("payment/alipay_return", '', '', true);
		}
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['input_charset'] = strtolower('utf-8');
		//ca证书路径地址，用于curl中ssl校验, 请保证cacert.pem文件在当前文件夹目录中
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipay_config['payment_type'] = "1";
		$alipay_config['service'] = "alipay.wap.create.direct.pay.by.user";

		/**************************请求参数**************************/
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $_POST['WIDout_trade_no'];
		//订单名称，必填
		$subject = $_POST['WIDsubject'];
		//付款金额，必填
		$total_fee = $_POST['WIDtotal_fee'];
		//$total_fee = 0.01;
		//收银台页面上，商品展示的超链接，必填
		$show_url = $_POST['WIDshow_url'];
		//商品描述，可空
		$body = $_POST['WIDbody'];
		/************************************************************/
		//构造要请求的参数数组，无需改动
		$parameter = array(
			"service" => $alipay_config['service'],
			"partner" => $alipay_config['partner'],
			"seller_id" => $alipay_config['seller_id'],
			"payment_type" => $alipay_config['payment_type'],
			"notify_url" => $alipay_config['notify_url'],
			"return_url" => $alipay_config['return_url'],
			"_input_charset" => trim(strtolower($alipay_config['input_charset'])),
			"out_trade_no" => $out_trade_no,
			"subject" => $subject,
			"total_fee" => $total_fee,
			"show_url" => $show_url,
			//"app_pay" 		 => "Y", //启用此参数能唤起钱包APP支付宝
			"body" => $body,
		);
		if($_POST['type'] == 'ads_order'){
			$this->abs_add_log();//订单支付日志
		}
		//建立请求
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
		echo $html_text;
	}
    
	//支付日志
	function add_log($order_ids){
		$orderid_list = explode("|", $order_ids);
		$data=array();
		for($i=0;$i<count($orderid_list);$i++){
			$order=db("mall_order")->where('id', $orderid_list[$i])->find();
			$score="0";
			if($order['give_score']){
				$score='+'.$score;
			}
			if($order['need_score']){
				$score='-'.$score;
			}
			$order_data = array(
			'type' 			=> input('type'),
			'member1'		=>$order['level1'],
			'member2'		=>$order['level2'],
			'member3'		=>$order['level3'],
			'price1'		=>$order['level1_money'],
			'price2'		=>$order['level2_money'],
			'price3'		=>$order['level3_money'],
			'pt_id'			=>$order['pt_id'],
			'pt_price'		=>$order['pt_money'],
			'co_id'			=>$order['co_id'],
			'co_price'		=>$order['co_money'],
			'sn' 			=> input('WIDout_trade_no'),
			'user_type' 	=> input('user_type'),
			'pay_type' 		=> input('pay_type'),
			'tid'			=> $order['id'],
			'order_ids'		=>$order['id'],
			'uid'			=> input('uid'),
			'price'			=> $order['total_price'],
			'add_time' 		=> now_time(),
			'score'			=> $score,
			'long_price'	=>$order['long_price'],
			'long_score'	=>$order['long_score'],
			'status'		=>1
			);
			$data[]=$order_data;
		}
		$res=db("mall_paylog")->insertAll($data);
		return $res;
	}

	public function alipay_noify() {
		$member_model=new Member();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		//计算得出通知验证结果
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if ($verify_result) {
			//验证成功
			//请在这里加上商户的业务逻辑程序代
			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
			//商户订单号
			$out_trade_no = $_POST['out_trade_no'];
			//支付宝交易号
			$trade_no = $_POST['trade_no'];
			//交易状态
			$trade_status = $_POST['trade_status'];

			if ($_POST['trade_status'] == 'TRADE_FINISHED') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			}
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			$member =$member_model-> dopay($out_trade_no);
			echo "success";
			return $this->toJson(200, '支付成功', $member);
			//请不要修改或删除
		} else {
			//验证失败
			echo "fail";
		}
	}
	
	
	public function alipay_return() {
		$member_model=new Member();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if ($verify_result) {//验证成功
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//商户订单号
			$out_trade_no = $_GET['out_trade_no'];
			//支付宝交易号
			$trade_no = $_GET['trade_no'];
			//交易状态
			$trade_status = $_GET['trade_status'];
			if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else {
				echo "trade_status=" . $_GET['trade_status'];
			}
			$member =$member_model-> dopay($out_trade_no);
		} else {
			//验证失败
			echo "fail";
		}
	}

	/**
	 * Post方法
	 * $body     商品描述
	 * $attach   附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
	 * $order_no 订单号
	 * $total_fee 价格
	 */
		public function wechat() {
			$this->check_order();
			header('Access-Control-Allow-Origin:*');
			import("payment.wxpay.lib.WxPayApi");
			import("payment.wxpay.JsApiPay");
			if(input('type') == 'ads_order'){
				$this->abs_add_log();//订单支付日志
			}
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody(input("WIDsubject"));
			// 商品补充说明
			$input->SetAttach(input("WIDbody"));
			// 商户订单号32位以下
			$input->SetOut_trade_no(input("WIDout_trade_no"));
			// 价格，单位分
			$input->SetTotal_fee(input("WIDtotal_fee")*100);
			//$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'api/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid(input("openid"));//("otx0ewIY-HKwa5p0gql3bDfp562A");
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo "jsonpCallback"."(".$jsApiParameters.")";
			exit;
	}

	public function wechat_notify() {
		import("payment.wxpay.wechat_callback");
		//获取支付回调结果。
		$notify = new \wechat_callback();
		
		$notify->Handle(false);
		
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = $notify->FromXml($xml);
		
		//处理回调
		if($data['return_code'] == "SUCCESS"){
			//查找当前支付日志状态
			$cut_paylog_info = db('mall_paylog')->where('sn',$data['out_trade_no'])->find();
			
			//判断当前是否支付完成
			if($cut_paylog_info['status'] != 2){
				$member_model=new Member();
				$member = $member_model->dopay($cut_paylog_info['sn']);
			}else{
				$rest = $notify->ToXml();
				echo $rest;
			}
		}
		
	}
}
